package com.hzy.servlet;

import com.hzy.pojo.Fruit;
import com.hzy.service.FruitService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Package: servlet
 * @ClassName: ListServlet
 * @Author: 862982795
 * @CreateTime: 2021/06/07 9:46
 * @Description:
 */
@WebServlet("/ListServlet")
public class ListServlet extends HttpServlet {
    Integer pageNo = 1;//默认的当前页码
    Integer pageSize = 2;//默认查询的记录数

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        FruitService service = new FruitService();
        Integer count = service.getCount();//总记录数

        String pageNoStr = req.getParameter("pageNo");//获取需要查询的页码
        if (pageNoStr != null) {
            pageNo = Integer.parseInt(pageNoStr);
        }
        String pageSizeStr = req.getParameter("pageSize");//获取每一页需要查询的记录数
        if (pageSizeStr != null) {
            pageSize = Integer.parseInt(pageSizeStr);
        }
        Integer pageNos = count % pageSize > 0 ? count / pageSize + 1 : count / pageSize;//总页码
        Integer pageBegin = (pageNo - 1) * pageSize;

        List<Fruit> list = service.getList(pageBegin, pageSize);
        System.out.println("pageBegin="+pageBegin+",pageSize="+pageSize+",pageNo="+pageNo);
        System.out.println("list.size()="+list.size());

        req.setAttribute("list", list);
        req.setAttribute("pageNo", pageNo);
        req.setAttribute("pageNos", pageNos);
        req.getRequestDispatcher("list.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
